package com.xiaoq.qiniu;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.qiniu.common.Config;
import com.qiniu.common.Zone;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.xiaoq.coms.RestException;
import com.xiaoq.coms.util.IdGenerator;

public class UploadUtil {
	
	 private static final String SECRETKEY = "doUlYCjtgFF-xDQQeX4-dhcivzdnI7HMI6oiC2IE";
	 private static final String ACCESSKEY = "VEtoPbtmSFhXPDrz9DNtPflvaVUjZ57a-aAB6Kut";
	
    //    需要压缩的文件大小
    private static final Long COMPRESSSIZE = 1024*1024*1L/4;//1024K
    //    限制文件上传的类型
    private static final List<String> SUFFIXLIST = new ArrayList<String>();
    static{
        SUFFIXLIST.add(".jpg");
        SUFFIXLIST.add(".gif");
        SUFFIXLIST.add(".jpeg");
        SUFFIXLIST.add(".bmp");
        SUFFIXLIST.add(".png");
		
		//设置区域
        Config.zone = Zone.zone1();
    }
    //七牛saves  压缩操作  参数可改(先做图片压缩吧，视屏压缩先不管了)
    private static final String fops = "imageMogr2/thumbnail/500x/strip/quality/50";
    private static final String fops2 = "avthumb/mp3";
    //转换通道
    private static final String PIPELINE = null;
    //秘钥
    private static Auth auth  = Auth.create(ACCESSKEY,SECRETKEY);
    private static Base64 base64 = new Base64();
    private static BucketManager bucketManager = new BucketManager(auth);
    private static UploadManager uploadManager = new UploadManager();

    /**
     * 将Amr转成Mp3
     * @param file
     * @param bucketName
     * @param domain
     * @return
     * @throws IOException
     */
	public static String amr2Mp3(File file, String originalName, String bucketName, String domain) throws IOException {

		if (file != null && !StringUtils.isBlank(bucketName)) {
			// 判断文件类型留给前端判断, 我需要上传图片和视屏。
			String key = base64.encodeAsString((originalName + System.currentTimeMillis()).getBytes());
			String pfops = fops2 + "|saveas/" + UrlSafeBase64.encodeToString(bucketName + ":" + key);
			Response response = null;
			response = uploadManager
					.put(file, key,
							auth.uploadToken(bucketName, null,
									3600, new StringMap().putNotEmpty("persistentOps", pfops)
											.putNotEmpty("savekey", key).putNotEmpty("persistentPipeline", PIPELINE),
									true));

			if (response != null && response.statusCode == 200) {
				return domain + "/" + key;
			}
		}
		return null;
	}
    
    //简单上传 超过限制大小 压缩
    public static String easyUploadByte(MultipartFile file, String bucketName, String domain) throws IOException {
        if(file != null  && !StringUtils.isBlank(bucketName)){
//            判断文件类型
//            isSuffix(file.getOriginalFilename());
        	// 判断文件类型留给前端判断, 我需要上传图片和视屏。
            String key = base64.encodeAsString((file.getOriginalFilename() + System.currentTimeMillis()).getBytes());
            String pfops  =  fops + "|saveas/"+ UrlSafeBase64.encodeToString(bucketName + ":" + key);
            Response response = null;
            if(file.getSize() > COMPRESSSIZE){
                //压缩上传
                 response = uploadManager.put(file.getBytes(),key,auth.uploadToken(bucketName,null,3600,new StringMap()
                         .putNotEmpty("persistentOps", pfops)
                         .putNotEmpty("savekey",key)
                         .putNotEmpty("persistentPipeline", PIPELINE), true));

            }else {
//                不压缩上传
                try {

                    response = uploadManager.put(file.getBytes(), key, auth.uploadToken(bucketName));
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            if(response != null && response.statusCode == 200){
                return domain +"/"+key;
            }
        }
            return null;
    }
    
    /**
     * File 上传
     * @param file
     * @param bucketName
     * @param domain
     * @return
     * @throws IOException
     */
    public static String easyUploadBytes(File file, String originalName,String bucketName, String domain) throws IOException {
        if(file != null  && !StringUtils.isBlank(bucketName)){
//            判断文件类型
//            isSuffix(file.getOriginalFilename());
        	// 判断文件类型留给前端判断, 我需要上传图片和视屏。
            String key = base64.encodeAsString((originalName + System.currentTimeMillis()).getBytes());
            String pfops  =  fops + "|saveas/"+ UrlSafeBase64.encodeToString(bucketName + ":" + key);
            Response response = null;
            if(file.length() > COMPRESSSIZE){
                //压缩上传
                 response = uploadManager.put(file,key,auth.uploadToken(bucketName,null,3600,new StringMap()
                         .putNotEmpty("persistentOps", pfops)
                         .putNotEmpty("savekey",key)
                         .putNotEmpty("persistentPipeline", PIPELINE), true));

            }else {
//                不压缩上传
                try {

                    response = uploadManager.put(file, key, auth.uploadToken(bucketName));
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            if(response != null && response.statusCode == 200){
                return domain +"/"+key;
            }
        }
            return null;
    }


    //生成一个html片段字符串，上传七牛生成一个html静态页面
    public static String stringUploadByte(String file, String bucketName, String domain) throws IOException {
    	String fileName = new IdGenerator().nextId()+System.currentTimeMillis()+".html";

        if(file != null  && !StringUtils.isBlank(bucketName)){
//            判断文件类型
//            isSuffix(fileName);
            String key = base64.encodeAsString((fileName + System.currentTimeMillis()).getBytes());
            String pfops  =  fops + "|saveas/"+ UrlSafeBase64.encodeToString(bucketName + ":" + key);
            Response response = null;
            if(file.length() > COMPRESSSIZE){
                //压缩上传
                 response = uploadManager.put(file.getBytes(),key,auth.uploadToken(bucketName,null,3600,new StringMap()
                         .putNotEmpty("persistentOps", pfops)
                         .putNotEmpty("savekey",key)
                         .putNotEmpty("persistentPipeline", PIPELINE), true));

            }else {
//                不压缩上传
                try {

                    response = uploadManager.put(file.getBytes(), key, auth.uploadToken(bucketName));
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            
          
            if(response != null && response.statusCode == 200){
                return domain +"/"+key;
            }
        }
            return null;
    }


    //覆盖上传 如果指定key的文件不存在 就新增指定key的文件到指定空间
    public static String overriedUploadByte(MultipartFile file ,String originalUrl,String bucketName,String domain) throws IOException {
        if(file == null || StringUtils.isBlank(bucketName)){
            return null;
        }
        isSuffix(file.getOriginalFilename());
        Response response ;
        String key = getKeyByUrl(originalUrl);
        if(file.getSize() > COMPRESSSIZE){
//            压缩覆盖上传
            StringMap stringMap = new StringMap();
            String pfops  =  fops + "|saveas/"+ UrlSafeBase64.encodeToString(bucketName + ":" + key);
            stringMap.putNotEmpty("persistentOps", pfops);
            stringMap.putNotEmpty("scope",bucketName + ":" + key);
            stringMap.putNotNull("insertOnly",0);
            stringMap.putNotEmpty("persistentPipeline",PIPELINE);
            response = uploadManager.put(file.getBytes(),key,auth.uploadToken(bucketName,key,3600,stringMap ,true));
        }else{
//            不压缩覆盖上传
             response = uploadManager.put(file.getBytes(), key, auth.uploadToken(bucketName, key));
        }
        return  response.statusCode == 200?domain + "/" + key:null;
    }



    //删除单个文件
    public static boolean  deleteFile(String bucketName,String key) throws QiniuException {
        if(StringUtils.isBlank(bucketName) || StringUtils.isBlank(key)){
            return false;
        }
        bucketManager.delete(bucketName,key);
        return true;
    }

    //目前不支持多文件上传，官方建议服务器端的多文件上传 采用循环的方式 发送多个上传请求。非服务器端上传 找相应的插件上传
    //断点上传 大文件 适用

    //根据url获取 图片的key
    public static String getKeyByUrl(String url){
        if(!StringUtils.isBlank(url)){
            return url.split(".com/")[1];
        }
        return  null;
    }

    //判断图片是否是图片
    public static boolean isSuffix(String name){
        if(StringUtils.isBlank(name)){
            throw new RestException(HttpStatus.BAD_REQUEST, "Mistake name");
        }
         String suffix =name.substring(name.lastIndexOf("."));
        if(!SUFFIXLIST.contains(suffix.toLowerCase())){
            throw new RestException(HttpStatus.BAD_REQUEST, "mistake file suffix");
        }
        return true;

    }
}

